package designpattern.prodecterconsumer;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.*;
//本代码模拟了采用生产者消费者模式对部署在不同服务器上的多个api进行请求，从而提升模型响应速度
public class NewContainer {
     Queue<String>urls=new LinkedList<>();
    private final int MAX=3;
    private int count=3;
    public synchronized String get(){
        while (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        String url=urls.poll();
        System.out.println(Thread.currentThread().getName()+"向"+url+"发送请求，生成问题");
        count--;
        this.notifyAll();
        return url;
    }
    public synchronized void add(String url){
        while (count==MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(Thread.currentThread().getName()+"向"+url+"请求完毕，放入队列中");
        urls.add(url);
        count++;
        this.notifyAll();
    }
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(10,15,60L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());
        NewContainer newContainer=new NewContainer();
        newContainer.urls.add("url1");
        newContainer.urls.add("url2");
        newContainer.urls.add("url3");
        Random random=new Random();
        for (int i = 0; i < 10; i++) {
                threadPoolExecutor.execute(()->{
                    String url=newContainer.get();
                    try {
                        Thread.sleep(random.nextInt(30000));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    newContainer.add(url);
                });
        }
    }
}
